const BaseService = require('./baseService')
const { Op } = require('sequelize')

class ArticleService extends BaseService {
	constructor(...args) {
		super(...args)
		this.modelName = 'Article'
	}
	/**
	 * 获取所有文章信息
	 * @param {*} options //查询条件
	 * @param {*} moduleObj
	 * @param {*} associateModalWhere 按分类查询
	 * @returns
	 */
	async list(options, moduleObj, associateModalWhere) {
		let other = {}
		if (associateModalWhere) {
			other['where'] = {
				[associateModalWhere.associateKey]: {
					[Op.eq]: [associateModalWhere.associateVal],
				},
			}
		}
		return await this.Util(options, other, null)
	}
	/**
	 * 通过文章id获取文章内容
	 * @param {*} id
	 * @returns
	 */
	async getInfoById(id) {
		const IsExisted = await this.IsExisted('Article', 'id', id)
		if (!IsExisted) return { flag: false, message: '文章不存在' }
		let options = {}
		if (id) {
			options['where'] = {
				id: {
					[Op.eq]: id,
				},
			}
		}
		const data = await this.Util(options, null, id)
		if (data) return { flag: true, message: '查询成功', data }
		else return { flag: true, message: '查询失败' }
	}
	/**
	 * 工具类
	 * @param {*} options//查询条件
	 * @param {*} other 按分类查询
	 * @param {*} id // 按照id查询
	 * @returns
	 */
	async Util(options, other, id) {
		if (id) {
			options['where'] = {
				id: {
					[Op.eq]: id,
				},
			}
		}
		return await this.ctx.model.Article.findAndCountAll({
			...options,
			include: [
				{
					model: this.ctx.model.Category,
					as: 'categories',
					...other,
					through: {
						attributes: [],
					},
				},
				{
					model: this.ctx.model.User,
					as: 'author',
					attributes: { exclude: ['password'] },
				},
				{
					model: this.ctx.model.Comment,
					as: 'comments',
					include: [
						{
							model: this.ctx.model.Reply,
							as: 'replies',
						},
					],
				},
				{
					model: this.ctx.model.ArticleLike,
					as: 'likes',
					attributes: {
						exclude: ['id', 'user_id'],
					},
					include: [
						{
							model: this.ctx.model.User,
							as: 'likeUser',
							attributes: { exclude: ['password'] },
						},
					],
				},
				{
					model: this.ctx.model.ArticleCollect,
					as: 'collects',
					include: [
						{
							model: this.ctx.model.User,
							as: 'collector',
							attributes: { exclude: ['password'] },
						},
					],
				},
			],
		})
	}
	/**
	 * 文章删除
	 *
	 * @param {*} ids
	 * @param {*} transactions 事务
	 *
	 */
	async delAll({ ids, transactions }) {
		let transaction = transactions
		try {
			if (!transactions) transaction = await this.ctx.model.transaction()

			for (let i = 0; i < ids.length; i++) {
				const id = ids[i]
				// 文章 id 数据是否存在
				const IsExisted = await this.IsExisted(this.modelName, 'id', id)
				// 只删除一条数据 并且文章不存在
				if (!IsExisted && ids.length == 1)
					return { flag: false, message: '文章不存在' }
				// 删除多条数据 其中出现一条 非法数据 跳过该条数据继续执行删除
				if (!IsExisted && ids.length != 1) continue
				// 执行主表删除

				const delMaster = await this.destroyOne(
					this.modelName,
					'id',
					id,
					transaction
				)

				if (!delMaster) throw Error
				// 删除改文章 分类信息
				const findCategoryArticle =
					await this.ctx.model.CategoryArticle.findAll({
						where: {
							article_id: id,
						},
					})
				if (findCategoryArticle.length) {
					let ids = findCategoryArticle.map((item) => item.dataValues.cate_id)
					const flag = await this.ctx.model.CategoryArticle.destroy({
						where: {
							cate_id: ids,
						},
						transaction,
					})
					if (!flag) throw Error
				}
				// 删除改文章评论
				const findComment = await this.ctx.model.Comment.findAll({
					where: {
						article_id: id,
					},
				})
				// console.log(findComment)
				if (findComment.length) {
					let ids = findComment.map((item) => item.dataValues.id)
					// 执行评论删除 同时删除评论的子评论
					const { flag, message } = await this.service.commentS.delAll({
						ids,
						transaction,
					})
					if (!flag) throw Error
				}
				// 删除该文章点赞
				const findArticleLike = await this.ctx.model.ArticleLike.findAll({
					where: {
						article_id: id,
					},
				})
				if (findArticleLike.length) {
					let ids = findArticleLike.map((item) => item.dataValues.id)
					const flag = await this.ctx.model.ArticleLike.destroy({
						where: {
							id: ids,
						},
						transaction,
					})

					if (!flag) throw Error
				}
				// 删除该文章收藏
				const findArticleCollect = await this.ctx.model.ArticleCollect.findAll({
					where: {
						article_id: id,
					},
				})
				if (findArticleCollect.length) {
					let ids = findArticleCollect.map((item) => item.dataValues.id)
					const flag = await this.ctx.model.ArticleCollect.destroy({
						where: {
							id: ids,
						},
						transaction,
					})
					if (!flag) throw Error
				}
			}
			if (!transactions) await transaction.commit()
			return {
				flag: true,
				message: '删除成功',
			}
		} catch (error) {
			if (!transactions) await transaction.rollback()
			console.log(error)
			return {
				flag: false,
				message: '删除失败。',
			}
		}
	}
}

module.exports = ArticleService
